package com.colabox.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gdata.client.docs.DocsService;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.data.docs.SpreadsheetEntry;
import com.google.gdata.data.spreadsheet.WorksheetEntry;

import org.json.*;

/*
 * http://code.google.com/apis/documents/docs/2.0/developers_guide_java.html#AuthClientLogin
 * docs api
 * 
 * 
 * 
 */
public class colaboxServ extends HttpServlet {
	private String captchaToken = null;
	private gdocs gdocsServies;

	private static final Logger log = Logger.getLogger(colaboxServ.class
			.getName());

	// private DocumentList documentList;
	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {

		JSONObject jsonRet = new JSONObject();
		
		if (req.getParameter("mod").equals("notepad")) {

			String s = req2string(req);

			try {
				log.info("post data : " + s);
				gdocsServies = new gdocs("colabox-notepad");

				JSONArray jsonA = new JSONArray(s);
				JSONObject jsonType = new JSONObject(jsonA.getString(0));
				
				if (jsonType.getString("Type").equals("testLogin")) {
					JSONObject jsonVal = new JSONObject(jsonA.getString(1));
					// System.out.println("-------u="+jsonVal.getString("Gusername"));
					// System.out.println("-------p="+jsonVal.getString("Gpassword"));
					String errRet="";
					String[] token={"",""};
					boolean b = gdocsServies.getAuthToken(jsonVal
							.getString("Gusername"), jsonVal
							.getString("Gpassword"),token,errRet);
					//System.out.println("-------p="+token[0]);
					
					if (b) {
						jsonRet.put("ret", "true");
						jsonRet.put("val", "true");
						jsonRet.put("token1", token[0]);
						jsonRet.put("token2", token[1]);
					}else{
						jsonRet.put("ret", "false");
						jsonRet.put("val", errRet);						
					}
					res.getWriter().print(jsonRet);
				}else if(jsonType.getString("Type").equals("autoSync")){
					JSONObject jsonToken = new JSONObject(jsonA.getString(1));
					
					boolean b = gdocsServies.setAuthToken(jsonToken.getString("Token1"), jsonToken.getString("Token2"));
					if (!b){
						jsonRet.put("ret", "false");
						jsonRet.put("val", "login error.");	
						res.getWriter().print(jsonRet);
						return;
					}else{
						JSONObject jsonSyncVal = new JSONObject(jsonA.getString(2));
						String id=jsonSyncVal.getString("id");
						String title=jsonSyncVal.getString("title");
						String content=jsonSyncVal.getString("content");
						String btime=jsonSyncVal.getString("btime");
						String ctime=jsonSyncVal.getString("ctime");
						String type=jsonSyncVal.getString("type");
						String deleteflag=jsonSyncVal.getString("deleteflag");
						String synccounts=jsonSyncVal.getString("synccounts");
						log.info("----"+id+"@"+title+"@"+content+"@"+btime+"@"+ctime+"@"+type+"@"+deleteflag+"------");
						String worksheetname=btime.substring(0,4);
						if (!gdocsServies.createSpreadsheet("Colabox-Notepad")){
							jsonRet.put("ret", "false");
							jsonRet.put("val", "createSpreadsheet error.");	
							res.getWriter().print(jsonRet);
							return;
						}
						log.info("----createSpreadsheet start------");
						if (!gdocsServies.createWorksheetEntry(worksheetname)){
							jsonRet.put("ret", "false");
							jsonRet.put("val", "createWorksheetEntry "+worksheetname+" error.");	
							res.getWriter().print(jsonRet);
							return;
						}
					
					    log.info("----createSpreadsheet ok------");
						if (!gdocsServies.createTable(worksheetname)){
							jsonRet.put("ret", "false");
							jsonRet.put("val", "createWorksheetEntry "+worksheetname+" error.");	
							res.getWriter().print(jsonRet);
							return;
						}
					
					   log.info("----createTable ok------");
						if (!gdocsServies.addTableField(id,title,content,btime,ctime,type,synccounts)){
							log.info("----addTableField ok------");
							jsonRet.put("ret", "false");
							jsonRet.put("val", "addField "+id+" error.");	
							res.getWriter().print(jsonRet);
							return;
						}else{
							jsonRet.put("ret", "true");
							jsonRet.put("val", id);	
							res.getWriter().print(jsonRet);
							return;
						}
						
					}
				}
				
			} catch (Exception e) {
				try{
					jsonRet.put("ret", "true");
					jsonRet.put("val", "json error :" + e.getMessage());	
					res.getWriter().print(jsonRet);
					log.info("json error :" + e.getMessage());				
					return;
				}catch(Exception e2){
				    return;
				}
				
				
			}

			
		} else {
			log.info("Invalid post Parameters.");
		}

		// obj.
	}

	public void testjson() {

		String s = "";// req2string(req);

		try {
			// get demo
			JSONArray jsonA = new JSONArray(s);
			String name = jsonA.getString(0);
			// String content="";
			JSONArray jsonA2 = new JSONArray();
			for (int i = 0; i <= jsonA.length() - 1; i++) {
				JSONObject jsonO = new JSONObject(jsonA.getString(i));
				String id = jsonO.getString("id");
				String title = jsonO.getString("title");
				String content = jsonO.getString("content");
				String type = jsonO.getString("type");
				String changetime = jsonO.getString("changetime");
				log.info("id=" + id + " title=" + title + " content=" + content
						+ " type=" + type + " changetime=" + changetime);

				JSONObject jsonO2 = new JSONObject();
				String tmpstr = content;
				jsonO2.put("id", 0);
				jsonO2.put("ret", tmpstr);

				jsonA2.put(jsonO2);

			}

			// put demo
			/*
			 * JSONObject jsonO2 = new JSONObject(); String tmpstr="";
			 * jsonO2.put("id", 0); jsonO2.put("ret", tmpstr);
			 * 
			 * JSONArray jsonA2 = new JSONArray(); for (int
			 * i=0;i<=jsonA.length()-1;i++) { jsonA2.put(jsonO2); }
			 */

			test();
			// res.getWriter().print(jsonA2);

		} catch (Exception e) {
			log.info("json error :" + e.getMessage());
		}

		log.info("post data : " + s);

		// obj.
	}

	private void test() {
		// dcoumentList.\
		login("untosil@gmail.com", "ihateself");
		try {

			// log.info(documentList.createFolder("CNotePad").getId());

			// log.info(documentList.createDocument("CNotePad-docs").getId());
			// log.info(gdocsServie.createSpreadsheet("Colabox-Notepad").getId());
			gdocsServies.createSpreadsheet("Colabox-Notepad");
			// WorksheetEntry wentry =
			// gdocsServies.createWorksheetEntry(null,"200909");
			// gdocsServies.createTable(wentry, "notepad", "200909");
		} catch (Exception e) {
			log.info("createSpreadsheet error " + e.getMessage());
		}

	}

	private void login(String username, String password) {
		try {
			// gdocsServies = new gdocs("colabox-notepad");

			// log.info("get token ok ");
			// documentList.login(username, password);

			// log.info("token="+gdocsServies.getAuthToken("",""));
		} catch (Exception e) {
			log.info("login error : " + e.getMessage());

		}

	}

	private String req2string(HttpServletRequest request) {
		StringBuffer json = new StringBuffer();
		String line = null;
		try {
			BufferedReader reader = request.getReader();
			while ((line = reader.readLine()) != null) {
				json.append(line);
			}
		} catch (Exception e) {
			log.info(" Error reading JSON string:  " + e.toString());

		}
		return json.toString();
	}

}